package 力扣;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-08-20
 * Time: 10:45
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class maximum_binary_tree {
    private static int findMaxIndex(int[] nums, int l, int r){
        int tmp = l;
        int max = nums[tmp];
        for(int i = l; i <= r; i++){
            if(nums[i] > max){
                max = nums[i];
                tmp = i;
            }
        }
        return tmp;
    }

    private static TreeNode construct(int[] nums, int l, int r){
        if(l > r){
            return null;
        }
        int maxIndex = findMaxIndex(nums, l, r);
        TreeNode node = new TreeNode(nums[maxIndex]);
        node.left = construct(nums, l, maxIndex - 1);
        node.right = construct(nums, maxIndex + 1, r);
        return node;
    }

    public static TreeNode constructMaximumBinaryTree(int[] nums) {
        int len = nums.length;
        return construct(nums, 0, len - 1);
    }

    public static void main(String[] args) {
        int[] nums = {3,2,1,6,0,5};
        constructMaximumBinaryTree(nums);
    }
}
